use redis_protocol::resp2::prelude::Frame;
use crate::prelude::*;
use std::collections::HashMap;
pub struct Hset();
pub struct Hget();
impl CommandService for Hset {
    fn process(&self, s: &Arc<dyn StorageService>, param: Frame) -> Option<Frame>
    {
        let mut p = FrameParser::new(param).unwrap();
        p.next_string().unwrap();

        let key = p.next_string().unwrap();
        let field = p.next_string().unwrap();
        let v = p.next_string().unwrap();

        let mut value = s.lookup(Key::STRING(key.clone())).map_or(
            HashMap::<String, String>::new(), 
            |v| match v{
                Value::HASH(r)=> r,
                _ => panic!("Invalid")
            }
        );

        value.insert(field, v);

        s.insert(Key::STRING(key), Value::HASH(value)).unwrap();
        Some(Frame::SimpleString(String::from("ok")))

    }
}


impl CommandService for Hget {
    fn process(&self, s: &Arc<dyn StorageService>, param: Frame) -> Option<Frame>
    {
        let mut p = FrameParser::new(param).unwrap();
        p.next_string().unwrap();

        let key = p.next_string().unwrap();
        let field = p.next_string().unwrap();

        s.lookup(Key::STRING(key.clone())).map_or(
            Some(Frame::Integer(0)), 
            |v| match v{
                Value::HASH(r)=> Some(Frame::SimpleString(r.get(&field).unwrap().to_string())),
                _ => panic!("Invalid")
            }
        )

    }
}